#include<iostream>
#include<string>
#include<sys/socket.h>
#include<sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<unistd.h>
#include<cstring>
void Usage(std::string proc)
{

}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }


    //tcp client要bind 但是不要显示bind
    struct sockaddr_in server;
    //构建目标主机的socket信息
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);
    int n = connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n < 0)
    {
        std::cerr<<"connect error"<<std::endl;
        exit(3);
    }

    while(true)
    {
        std::cout<<"Plase Enter# ";
        std::string outstring;
        std::getline(std::cin,outstring);
        ssize_t s = send(sockfd, outstring.c_str(), sizeof(outstring),0);
        if(s > 0)
        {
            char buffer[1024];
            ssize_t m = recv(sockfd, buffer, sizeof(buffer)-1, 0);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout<<buffer<<std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    shutdown(sockfd, SHUT_RD);
    return 0;
}